﻿$(function () {
    var inside = false;
    $("g path").each(function () {
        $(this).mouseenter(function () {
            addHighlight($(this).attr("d"));
        }).mouseleave(function () {
            $("path[class='selected']").remove();
        });
        ;
    });
    $("g rect").each(function () {
        var self = $(this);
        $(this).nextAll("text").first().mouseenter(function (e) {
            if (!inside) {
                inside = true;
                $(self).trigger(e.type);
            }
        }).mouseleave(function (e) {
            $(self).trigger(e.type);
            inside = false;
        });
        $(this).mouseenter(function () {
            var group = $(this).attr('g');
            var elements = $("g path[g='" + group + "']");
            addHighlight($(elements).first().attr("d"));
        }).mouseleave(function () {
            $("path[class='selected']").remove();
        });
    });

    function extractFromArc(stringPath) {
        var match = /A (.*?){1} (.*?){1} (0 |1 ){3}(.*?){1} (.*?){1} L (.*?){1} (.*?){1} (.*?){1} (.*?){1} /i.exec(stringPath);

        return {
            rx: parseFloat(match[1]),
            ry: parseFloat(match[2]),
            x1: parseFloat(match[4]),
            y1: parseFloat(match[5]),
            x2: parseFloat(match[8]),
            y2: parseFloat(match[9]),
            cx: parseFloat(match[6]),
            cy: parseFloat(match[7]),

            angleBegin: function () {
                return Math.asin(((this.x2 - this.cx) / this.rx).toFixed(6));
            },
            angleEnd: function () {
                return Math.asin(((this.x1 - this.cx) / this.rx).toFixed(6));
            }
        };
    }

    function createSVG(tag) {
        return document.createElementNS('http://www.w3.org/2000/svg', tag);
    }

    function addHighlight(stringPath, plus) {
        var r = extractFromArc(stringPath);
        plus = plus || 2;
        var begin = r.angleBegin();
        var end = r.angleEnd();
        var modifier = 1;
        var bottom = 0;
        if (begin < end) {
            var temp = begin;
            begin = end;
            end = temp;
            modifier = -1;
            bottom = 1;
        }

        x1 = r.cx + (r.rx + plus) * Math.sin(begin);
        y1 = r.cy - (r.ry + plus) * Math.cos(begin) * modifier;
        x2 = r.cx + (r.rx + plus) * Math.sin(end);
        y2 = r.cy - (r.ry + plus) * Math.cos(end) * modifier;

        $(createSVG("path")).attr("class", "selected").attr('style', "stroke:red; fill:none").attr("d", "M" + r.cx + "," + r.cy + " M" + x1 + "," + y1 + " A" + r.rx + "," + r.ry + " 0 0 " + bottom + " " + x2 + "," + y2).appendTo($("g"));
    }
});